package com.cloudstore.eccom.gyxy.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import weaver.conn.RecordSet;
import weaver.general.Util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;


public class MessageUtil {

    private final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
    private final static String PREFIX = "--";
    private final static String LINE_END = "\r\n";

    public static String getToken(String url, String par) {
        String result = "";
        HttpURLConnection httpConn = null;
        DataOutputStream out = null;
        BufferedReader in = null;
        try {
            URL urlObject = new URL(url);
            httpConn = (HttpURLConnection) urlObject.openConnection();
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpConn.setRequestMethod("POST");
            httpConn.setReadTimeout(30000);
            httpConn.setConnectTimeout(30000);
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);

            out = new DataOutputStream(httpConn.getOutputStream());
            if (par != null) {
                out.write(par.getBytes("UTF-8"));
            }
            out.flush();
            out.close();

            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result = result + inputLine;
            }
            in.close();
            httpConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;

    }

    public static String sendRequest(String requestUrl, Map<String, String> requestText, Map<String, MultipartFile> requestFile) {
        HttpURLConnection conn = null;
        InputStream input = null;
        OutputStream os = null;
        BufferedReader br = null;
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            conn.connect();
            os = new DataOutputStream(conn.getOutputStream());
            writeParams(requestText, os);
            writeFile(requestFile, os);
            String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
            os.write(endTarget.getBytes());
            os.flush();
            if (conn.getResponseCode() == 200) {
                input = conn.getInputStream();
            } else {
                input = conn.getErrorStream();
            }

            br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            System.out.println("######" + buffer.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                    conn = null;
                }

                if (os != null) {
                    os.close();
                    os = null;
                }

                if (br != null) {
                    br.close();
                    br = null;
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer.toString();
    }

    private static void writeParams(Map<String, String> requestText, OutputStream os) {
        try {
            String msg = "请求文本参数部分:\n";
            if (requestText == null || requestText.isEmpty()) {
                msg += "空";
            } else {
                StringBuilder requestParams = new StringBuilder();
                Iterator<Entry<String, String>> it = requestText.entrySet()
                        .iterator();
                while (it.hasNext()) {
                    Entry<String, String> entry = it.next();
                    requestParams.append(PREFIX).append(BOUNDARY)
                            .append(LINE_END);
                    requestParams
                            .append("Content-Disposition: form-data; name=\"")
                            .append(entry.getKey()).append("\"")
                            .append(LINE_END);
                    requestParams.append(
                            "Content-Type: text/plain; charset=utf-8").append(
                            LINE_END);
                    requestParams.append("Content-Transfer-Encoding: 8bit")
                            .append(LINE_END);
                    requestParams.append(LINE_END);
                    requestParams.append(entry.getValue());
                    requestParams.append(LINE_END);
                }
                os.write(requestParams.toString().getBytes());
                os.flush();
                msg += requestParams.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeFile(Map<String, MultipartFile> requestFile, OutputStream os) {
        InputStream is = null;
        try {
            String msg = "请求上传文件部分:\n";
            if (requestFile == null || requestFile.isEmpty()) {
                msg += "空";
            } else {
                StringBuilder requestParams = new StringBuilder();
                Iterator<Entry<String, MultipartFile>> it = requestFile
                        .entrySet().iterator();
                while (it.hasNext()) {
                    Entry<String, MultipartFile> entry = it.next();
                    if (entry.getValue() == null) {
                        continue;
                    }
                    requestParams.append(PREFIX).append(BOUNDARY)
                            .append(LINE_END);
                    requestParams
                            .append("Content-Disposition: form-data; name=\"")
                            .append(entry.getKey()).append("\"; filename=\"")
                            .append(entry.getValue().getOriginalFilename())
                            .append("\"").append(LINE_END);
                    requestParams.append("Content-Type:")
                            .append(entry.getValue().getContentType())
                            .append(LINE_END);
                    requestParams.append("Content-Transfer-Encoding: 8bit")
                            .append(LINE_END);
                    requestParams.append(LINE_END);
                    os.write(requestParams.toString().getBytes());
                    os.write(entry.getValue().getBytes());
                    os.write(LINE_END.getBytes());
                    os.flush();
                    msg += requestParams.toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static JSONObject getNodeBase(String requestid) {
        JSONObject dataJson = new JSONObject();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select n.id,n.nodename,b.currentnodetype,b.requestname from workflow_requestbase b left join workflow_nodebase n on b.currentnodeid=n.id where b.requestid=?", requestid);
        rs.next();
        dataJson.put("nodeid", Util.null2String(rs.getString("id")));
        dataJson.put("currentnodetype", Util.null2String(rs.getString("currentnodetype")));
        dataJson.put("nodename", Util.null2String(rs.getString("nodename")));
        dataJson.put("requestname", Util.null2String(rs.getString("requestname")));
        return dataJson;
    }

    public static String getDayHourMinute(String datetime1, String datetime2) {
        String datetime = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(datetime1);
            Date date2 = sdf.parse(datetime2);
            // 获取时间戳
            long timestamp1 = date1.getTime();
            long timestamp2 = date2.getTime();

            // 计算两个时间戳的差值
            long diff = Math.abs(timestamp1 - timestamp2);

            // 计算天数
            long days = diff / (24 * 60 * 60 * 1000);

            // 计算小时数
            long hours = (diff / (60 * 60 * 1000)) % 24;

            // 计算分钟数
            long minutes = (diff / (60 * 1000)) % 60;

            // 计算秒数
            long seconds = (diff / 1000) % 60;

            // 打印结果
            datetime = days + "天" + hours + "小时" + minutes + "分钟";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return datetime;
    }
}
